package com.gsdse.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gsdse.pojo.ReturnData;
import com.gsdse.pojo.User;
import com.gsdse.pojo.wxuser;
import com.gsdse.service.WxuserService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class WxController {

    // 定义一个方法来保存用户信息到数据库或者缓存中
    @Autowired
    private WxuserService wxuserService;
    // 这是一个你自己的Service类，用于处理用户数据的增删改查操作

    @RequestMapping("/wechatLogin")
    public ReturnData wechatLogin(String code) {
        ReturnData res = new ReturnData();
//        log.error("进来了");

        final OkHttpClient okHttpClient =
                new OkHttpClient.Builder().connectTimeout(1, TimeUnit.MINUTES).readTimeout(1, TimeUnit.MINUTES).writeTimeout(1, TimeUnit.MINUTES).build();


        //        接收前端数据
        String appid = "wx96f760966921f98a";
        String secret = "d9c11ca8780a8207b9bad199682904f9";
        String js_code = code;
        String wxErrmsg = "";
//        https://api.weixin.qq.com/sns/jscode2session?appid=<AppId>&secret=<AppSecret>&js_code=<code>&grant_type=authorization_code
        if (js_code != null) {
            String code2SessionURL =
                    "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type=authorization_code";
            Request okrequest = new Request.Builder().url(code2SessionURL).get().build();
            //4.创建一个call对象,参数就是Request请求对象
            Call call = okHttpClient.newCall(okrequest);
            String openid = "";
            String name = "";
            String respData = "";
            try {
                Response okresponse = call.execute();
                if (okresponse.isSuccessful()) {
                    respData = okresponse.body().string();
                    System.out.println(respData);
                    JSONObject jsonObject = JSONObject.parseObject(respData);
                    if (jsonObject.getString("openid") != null) {
                        openid = jsonObject.getString("openid");
                        name = jsonObject.getString("nickname");
                        wxuser user = wxuserService.SelectWxuser(openid);
                        if (user != null) {
                            //用户已记录=>登录
                            res.setCode(0);
                            res.setMsg("微信用户已存在");
                            res.setData(user);
                            return res;
                        } else {
                            //用户未记录=>记录=>登录
//                            确保微信的接口有返回openid
                            if (openid != null) {
                                wxuser newUser = new wxuser();
                                newUser.setOpenid(openid);
                                newUser.setNickName(name);
                                wxuserService.InsertWxuser(newUser);
                                res.setCode(1);
                                res.setMsg("未记录用户，创建用户完成");
                                res.setData(newUser);
                                return res;
                            } else {
                                res.setCode(2);
                                res.setMsg("openid为null");
                                res.setData(null);
                                return res;
                            }
                        }
                    } else {
                        wxErrmsg = jsonObject.getString("errmsg");
                        System.out.println(wxErrmsg);
                        res.setCode(3);
                        res.setMsg("微信接口返回errcode非0");
                        res.setData(wxErrmsg);
                        return res;
                    }

                } else {
                    System.out.println("服务端错误");
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            String string_date = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            string_date = sdf.format(new Date());

            System.out.println("/wxLogin" + "【" + string_date + "】收到js_code:" + js_code);
            //        调用Mapper接口

        } else {
            //接收到js_code为null
            res.setCode(4);
            res.setMsg("js_code为null");
            res.setData(null);
            return res;
        }
        return res;
    }

    //根据openId查找用户
    @RequestMapping("/selectUserByOpenid")
    public ReturnData selectAspiration(String openid) {
        ReturnData res = new ReturnData();
        if (StringUtils.isEmpty(openid)) {
            res.setCode(2);
            res.setMsg("参数为空");
            return res;
        }
        wxuser select = wxuserService.SelectWxuser(openid);
        if (select == null) {
            res.setCode(1);
            res.setMsg("查询错误，结果为空");
            return res;
        } else {
            res.setCode(0);
            res.setMsg("查询成功");
            res.setData(select);
            return res;
        }

    }

    @RequestMapping("/updateUserByOpenid")
    public ReturnData updateWxUser(wxuser wxuser) {
        ReturnData res = new ReturnData();
        String openid = wxuser.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            res.setCode(2);
            res.setMsg("openid为空");
            return res;
        }
        Boolean a = wxuserService.UpdateWxuser(wxuser);
        if (a) {
            res.setCode(0);
            res.setMsg("修改成功");
            return res;
        } else {
            res.setCode(1);
            res.setMsg("修改失败");
            return res;
        }

    }

}